import { createClient, SetOptions } from "redis";
const { REDIS_PORT, REDIS_HOST, REDIS_PASS } = process.env;

const client = createClient({
  password: REDIS_PASS,
  socket: {
    host: REDIS_HOST,
    port: REDIS_PORT as any,
  },
});

export enum RedisBasicsConfig {
  /**
   * 默认过期时间 7天
   */
  expireTime = 7 * 24 * 60,

  signExpireTime = 17 * 10,

  TOKEN = "user_token",
  SIGN = "sign",

  basicsDataBase = 0,
  taskDataBase = 1,
}

export async function useRedis() {
  client.on("error", (err) => console.log("Redis Client Error", err));
  await client.connect();
}
export type RedisCommandArgument = string | Buffer;

/**
 * 设置redis缓存
 * @param key redis表明
 * @param value
 * @param db 数据库
 * @param options
 * @param expireTime
 * @returns
 */
export function useSetRedisValue(
  key: RedisCommandArgument,
  value: any,
  db: number = RedisBasicsConfig.basicsDataBase,
  options?: SetOptions,
  expireTime?: number
) {
  return new Promise(async (resolve, reject) => {
    try {
      // 选择缓存的数据库
      await client.select(db);
      let result;
      if (typeof value === "string") {
        result = await client.set(key, value, options);
      }
      if (typeof value === "object") {
        result = await client.set(key, JSON.stringify(value), options);
      }
      resolve(result);
      if (expireTime) client.expire(key, expireTime);
    } catch (error) {
      reject(error);
    }
  });
}

/**
 * 获取redis缓存
 * @param key redis缓存名称
 * @returns
 */
export async function useGetRedisValue(key: RedisCommandArgument) {
  return await client.get(key);
}

/**
 * 设置token
 * 默认过期时间 7天
 * @param value token
 * @param options
 */
export async function useSetToken(value: string, options?: SetOptions) {
  await client.set(RedisBasicsConfig.TOKEN, value, options);
  client.expire(RedisBasicsConfig.TOKEN, 180);
}

/**
 * 设置sign
 * 默认过期时间 7天
 * @param value token
 * @param options
 */
export async function useSetSign(value: string, options?: SetOptions) {
  await client.set(RedisBasicsConfig.SIGN, value, options);
  client.expire(RedisBasicsConfig.SIGN, RedisBasicsConfig.signExpireTime);
}

/**
 * @设置sign
 * 默认过期时间 180秒
 */
export async function useGetSign() {
  return await client.get(RedisBasicsConfig.SIGN);
}

/**
 * 获取所有的任务
 * @param db 目标数据库
 */
export function useGetALLTask(db: number = 1): Promise<Array<string>> {
  return new Promise((resolve, reject) => {
    client.select(db).then(() => {
      client.keys("*").then(resolve).catch(reject);
    });
  });
}
